from fastapi import FastAPI, Cookie, Response, Request
from redis import Redis
from starlette_session import SessionMiddleware, BackendType

app = FastAPI()

redis_client = None

try:
    redis_client = Redis(host='localhost', port=6379, db=0)
    print("成功链接redis!")
except ImportError:
    print("链接失败！请安装redis或者运行redis-server！")

app.add_middleware(
    SessionMiddleware,
    secret_key="your_secret_key",
    cookie_name="session_cookie_name",
    backend_type=BackendType.redis,
    backend_client=redis_client
)


@app.get("/")
async def read_root():
    return {"Hello": "World"}


# 获取cookie
@app.get("/get_cookie/")
async def get_cookie(my_cookie: str = Cookie(None)):
    return {"my_cookie": my_cookie}


# 设置cookie
@app.get("/set_cookie/")
async def set_cookie(response: Response):
    response.set_cookie(key="my_cookie",  # 键
                        value="Pythin_FastAPI",  # 值
                        max_age=60 * 60 * 24  # 过期时间
                        )
    return {"message": "Cookie set"}


# 设置session
@app.get("/set_session/")
async def set_session(request: Request):
    request.session.update({"key": "azmat"})
    return {"status": "Session value set"}


# 获取session
@app.get("/get_session")
async def get_session(request: Request):
    return {"session_data": request.session.get("key", "Value not found")}


# 删除session
@app.get("/del_session_key")
async def del_session_key(request: Request, key: str):
    if key in request.session:
        del request.session[key]
        return {"status": f"Key '{key}' removed from session."}
    return {"status": f"Key '{key}' not found in session."}


# 删除所有session
@app.get("/clear_session")
async def clear_session(request: Request):
    request.session.clear()
    return {"status": "Session cleared"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)
